package com.maixun.lib_base.utils

import android.content.Context
import android.content.SharedPreferences

/**
 * 作者：Lmoumou
 * 时间：2020/9/3 10:44
 */
class SharedPrefUtil private constructor(name: String) {

    companion object {

        private var context: Context? = null

        fun init(context: Context) {
            Companion.context = context
        }

        fun open(name: String): SharedPrefUtil {
            synchronized(this) {
                if (context == null) {
                    throw RuntimeException("Must call init(Context context) at first")
                }
            }

            return SharedPrefUtil(name)
        }
    }

    private var prefrence: SharedPreferences

    init {
        prefrence = context!!.getSharedPreferences(name, Context.MODE_PRIVATE)
    }

    /**
     * 存放String
     */
    fun putString(key: String, value: String) {
        val editor = prefrence.edit()
        editor.putString(key, value)
        editor.apply()
    }

    /**
     * 获取String
     *
     *
     * 默认返回""
     */
    fun getString(key: String): String {
        return prefrence.getString(key, "") ?: ""
    }

    /**
     * 存放Int
     */
    fun putInt(key: String, value: Int) {
        val editor = prefrence.edit()
        editor.putInt(key, value)
        editor.apply()
    }


    /**
     * 获取Int
     *
     *
     * 默认返回 0
     */
    fun getInt(key: String): Int {
        return prefrence.getInt(key, 0)
    }

    fun putLong(key: String, value: Long) {
        val editor = prefrence.edit()
        editor.putLong(key, value)
        editor.apply()
    }

    fun getLong(key: String): Long {
        return prefrence.getLong(key, 0)
    }

    /**
     * 存放布尔值
     *
     * @param key
     * @param value
     */
    fun putBoolean(key: String, value: Boolean) {
        val editor = prefrence.edit()
        editor.putBoolean(key, value)
        editor.apply()
    }

    /**
     * 获取布尔值
     *
     * @param key
     * @return
     */
    fun getBoolean(key: String): Boolean {
        return prefrence.getBoolean(key, false)
    }

    /**
     * 移除对象
     */
    fun remove(key: String) {
        val editor = prefrence.edit()
        editor.remove(key)
        editor.apply()
    }

}